#coding=utf-8
import m3u8
import os,urllib
from array import *;
import subprocess 
import queue,threading
from time import ctime,sleep
import sys;


class downloadM3u8():

	def __init__(self):
		self.isComplate=True;
		self.dataQueue = queue.Queue(0);
		self.complateQueue = queue.Queue(0);
		self.size = 0;
		self.index = 0;
		self.videodir = "video";
		self.files = [];


	def downLoadPicFromURL(self,downUrl,index):  
		startIndex=downUrl.rfind("/")
		file_name=downUrl[startIndex+1:];#文件名，包含文件格式

		dest_dir=os.path.join(self.dirstr,file_name);
		if not os.path.exists(dest_dir):
			print("download:"+file_name+"size:"+str(self.size));
			urllib.request.urlretrieve(downUrl,dest_dir)
		
		self.complateFiles.append(dest_dir);
		if len(self.complateFiles) == self.size:
			if not os.path.exists(self.videodir):
				os.makedirs(self.videodir)
			self.concat_ts(self.files,self.videodir + "/"+ str(self.id)+".mp4")


	#获取M3U8源地址
	def getM3u8DownloadUrl(self):
		m3u8_obj = m3u8.load(self.m3u8url)  # this could also be an absolute filename
		index=0;
		startIndex=self.m3u8url.rfind("/");
		if startIndex < 0 or len(m3u8_obj.segments) == 0:
			print("url错误");
			return;

		basePath=url[:startIndex+1];

		if not os.path.exists(self.dirstr):
					os.makedirs(self.dirstr) 

		for tss in m3u8_obj.segments: #
				downUrl=basePath+tss.uri;
				startIndex=downUrl.rfind("/")
				file_name=downUrl[startIndex+1:];#文件名，包含文件格式
				
				dest_dir=os.path.join(self.dirstr,file_name);
				self.files.append(dest_dir);
				self.dataQueue.put(downUrl);
				index+=1;
		self.size=self.dataQueue.qsize();
		self.isComplate=False;
		return self.dataQueue


	def handelQueue(self):
		while True:
			if not self.dataQueue.empty():
				url=self.dataQueue.get();
				index=self.index;
				self.downLoadPicFromURL(url,index);
				self.index+=1;#全局变量记录
			else:
				sleep(3)

	#启动线程
	def startTreads(self): 
		threads=[];
		for x in range(1,5):
			t1 = threading.Thread(target=self.handelQueue)
			threads.append(t1)
			pass
		for t in threads:
			t.setDaemon(True)
			t.start()

	#主要main方法
	def main(self,dirstr,m3u8url,_id):

		self.dataQueue = queue.Queue(0);
		self.complateQueue = queue.Queue(0);
		self.size = 0;
		self.index = 0;

		self.dirstr=dirstr;
		self.m3u8url=m3u8url;
		self.complateFiles=[];
		self.id=_id;
		self.getM3u8DownloadUrl();#获取下载数据
		sleep(10)
		while not self.isComplate:
			sleep(3)
			pass

	def concat_ts(self,ts_parts, output = None):
	    assert ts_parts, 'no ts files found'
	    import os.path
	    if not output:
	        output = guess_output(ts_parts)
	    elif os.path.isdir(output):
	        output = os.path.join(output, guess_output(ts_parts))
	   
	    print('Merging video parts...'+ output)

	    if not os.path.exists(output):
		    ts_out_file = open(output, "wb")
		    for ts_in in ts_parts:
		        ts_in_file = open(ts_in, "rb")
		        print("Merging:" + ts_in);
		        ts_in_data = ts_in_file.read()
		        ts_in_file.close()
		        ts_out_file.write(ts_in_data)
		    ts_out_file.close()

	    for part in ts_parts:
	    	os.remove(part)
	    self.complateFiles=[];
	    self.files=[];
	    self.isComplate=True;
	    return output

if __name__ == '__main__':
	dirstr="tmp";
	videodir="video";
	f = open("live.txt")             # 返回一个文件对象
	line = f.readline()             # 调用文件的 readline()方法
	while line:
		url = "http://record2.inke.cn/record_" + line + "/" + line + ".m3u8?uid=0";
		_down=downloadM3u8();#
		_down.videodir = videodir;
		_down.startTreads();#启动线程
		_down.main(dirstr,url,line);

		line = f.readline()
	else:
		print("参数错误");
